package com.chenc.unitdemo.jwt.interceptor;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.chenc.unitdemo.jwt.dto.UserLoginDto;
import com.chenc.unitdemo.jwt.golbal.BusinessException;
import com.chenc.unitdemo.jwt.service.JWTService;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @ClassName
 * @Describtion:
 * @Author:Chenc
 * @Date:2023/12/18 14:59
 * @Version 1.0
 */
@Component
public class JWTInterceptor implements HandlerInterceptor {

    @Resource
    JWTService jwtService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        //获取token
        String token = request.getHeader("token");
        if (StringUtils.isEmpty(token)){
            throw new BusinessException("请先登录后再操作");
        }
        UserLoginDto userLoginDto = jwtService.verfyTokenAndcheckRedisToken(token);
        if (null == userLoginDto){
            throw new BusinessException("请先登录后再操作");
//            return false;
        }
        request.setAttribute("userInfo",userLoginDto);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {


    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws IOException {

    }


}
